import React, { Component } from 'react';
import { store, positionsStore } from './store';
import { hasSame } from './utils';

export default class Square extends Component<any> {
  public state = {
    hovering: false
  }

  public catch:any = {}

  public ref:any

  public componentDidMount(){
    this.catch.offsetLeft = this.ref.offsetLeft
    this.catch.offsetTop = this.ref.offsetTop
    this.catch.clientHeight = this.ref.clientHeight
    this.catch.clientWidth = this.ref.clientWidth
    const currentPositions:any = [
      [this.catch.offsetLeft, this.catch.offsetTop],
      [this.catch.offsetLeft+ this.catch.clientWidth, this.catch.offsetTop],
      [this.catch.offsetLeft, this.catch.offsetTop + this.catch.clientHeight],
      [this.catch.offsetLeft + this.catch.clientWidth, this.catch.offsetTop + this.catch.clientHeight],
    ]
    store.subscribe(({positions}) => {
      if (hasSame(positions, currentPositions)){
        this.setState({hovering: true})
        positionsStore.next({key:currentPositions,value:true,name:this.props.x.toString()+this.props.y})
      } else {
        positionsStore.next({key:currentPositions,value:false,name:this.props.x.toString()+this.props.y})
        this.setState({hovering: false,})
      }
    })
  }

  public render() {
    const fill = (this.props.x + this.props.y)%2 ? 'black' : 'white';
    const stroke = this.state.hovering ? 'red' : 'yellow';


    return <div ref={(ref) => this.ref = ref} style={{
      backgroundColor: fill,
      color: stroke,
      width: '10%',
      height: '10%',
      display: 'inline-block'
    }}>
      {this.props.x},{this.props.y}
    </div>
  }
}